﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yunchang;
namespace AutoChess
{
    public class AutoChessPlayerListPage : Page
    {
        public GameObject SelectFight, SelectChoose;

        public Transform itemRoot;
        public PlayerListItem itemPrefab;

        private List<PlayerListItem> cacheItem = new List<PlayerListItem>();

        public GameObject btnLeft, btnRight;
        public ScrollRect btnScrollRect;
        private void Update()
        {
            UICommonMethod.UpdateScrollerArrows(btnScrollRect, btnLeft, btnRight, true);
        }
        protected override void DoOpen()
        {
            EventManager.AddEventListener(CommonEvent.ON_AUTOCHESS_SWITCH_BATTLE, Close);
            base.DoOpen();
            var list = AutoChessManager.Ins.cacheData.GetAllPlayerList();
            ShowPlayerList(list);
            SwitchToFightHero();
        }
        protected override void DoClose(bool immediately)
        {
            base.DoClose(immediately);
            EventManager.RemoveEventListener(CommonEvent.ON_AUTOCHESS_SWITCH_BATTLE, Close);
        }

        public void SwitchToFightHero()
        {
            SelectFight.SetActive(true);
            SelectChoose.SetActive(false);

            foreach (var item in cacheItem)
            {
                var playerData = AutoChessManager.Ins.cacheData.GetPlayerData(item.playerGuid);
                item.SwitchToFightHero(playerData);
            }
        }
        public void SwitchToChooseHero()
        {
            SelectFight.SetActive(false);
            SelectChoose.SetActive(true);

            foreach (var item in cacheItem)
            {
                var playerData = AutoChessManager.Ins.cacheData.GetPlayerData(item.playerGuid);
                item.SwitchToChooseHero(playerData);
            }
        }

        private void ShowPlayerList(List<ACPlayerData> playerList)
        {
            for (int i = 0; i < playerList.Count; i++)
            {
                var item = GetPlayerItem(i);
                item.ResetPlayerInfo(playerList[i]);
            }
        }

        private PlayerListItem GetPlayerItem(int i)
        {
            if (cacheItem.Count > i)
            {
                return cacheItem[i];
            }
            var item = Instantiate<PlayerListItem>(itemPrefab, itemRoot);
            item.gameObject.SetActive(true);
            cacheItem.Add(item);
            return item;
        }
    }
}